package com.example.heimashop.view.activity;

import android.content.Intent;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.heimashop.base.BaseActivity;
import com.example.heimashop.databinding.ActivityProductListBinding;
import com.example.heimashop.utils.ToastUtils;
import com.example.heimashop.view.adapter.ProductAdapter;
import com.example.heimashop.viewmodel.ProductViewModel;

/**
 * 商品列表页面
 * 页面8: ProductListActivity - 商品列表页面
 */
public class ProductListActivity extends BaseActivity<ActivityProductListBinding> {

    private ProductViewModel viewModel;
    private ProductAdapter productAdapter;
    private int categoryId;

    @Override
    protected ActivityProductListBinding getViewBinding() {
        return ActivityProductListBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        viewModel = new ViewModelProvider(this).get(ProductViewModel.class);

        // 获取分类信息
        categoryId = getIntent().getIntExtra("categoryId", 0);
        String categoryName = getIntent().getStringExtra("categoryName");
        binding.tvTitle.setText(categoryName);

        // 初始化适配器
        productAdapter = new ProductAdapter();
        binding.rvProducts.setLayoutManager(new GridLayoutManager(this, 2));
        binding.rvProducts.setAdapter(productAdapter);
    }

    @Override
    protected void initData() {
        viewModel.productsLiveData.observe(this, products -> {
            if (products != null) {
                productAdapter.setData(products);
            }
        });

        viewModel.errorLiveData.observe(this, error -> {
            if (error != null) {
                ToastUtils.showShort(this, error);
            }
        });

        // 加载商品列表
        viewModel.getProductList(categoryId, 1);
    }

    @Override
    protected void initListener() {
        binding.ivBack.setOnClickListener(v -> finish());

        productAdapter.setOnItemClickListener(product -> {
            Intent intent = new Intent(this, ProductDetailActivity.class);
            intent.putExtra("productId", product.getGoodsId());
            startActivity(intent);
        });
    }
}
